﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wildweeds.SSO.Common;
using Wildweeds.SSO.FirstWebSite.SSOAuth;
using System.Configuration;

namespace Wildweeds.SSO.FirstWebSite
{
    public partial class Site : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SSOAuth.UserInfo userInfo = Session["user"] as SSOAuth.UserInfo;
            if (userInfo == null)
            {
                Guid token = ConvertHelper.GetGuid(Context.Request.QueryString["token"], Guid.Empty);
                if (token == Guid.Empty)
                {
                    string errorMsg = Context.Request.QueryString["errormsg"];
                    string SSOUrl = ConfigurationManager.AppSettings["SSOUrl"];
                    if (string.IsNullOrWhiteSpace(errorMsg))
                        Response.Redirect(SSOUrl+"Login.aspx?ReturnUrl=" + Request.Url.AbsoluteUri);
                    else
                        Response.Write("登陆出错：" + errorMsg);
                }
                else
                {
                    using (SSOAuth.AuthServiceClient client = new SSOAuth.AuthServiceClient())
                    {
                        AuthResult result = client.ValidateToken(token);
                        if (!string.IsNullOrWhiteSpace(result.ErrorMsg))
                        {
                            Response.Write("Token验证过程失败：" + result.ErrorMsg);
                        }
                        else
                        {
                            Session["user"] = result.User;                            
                            Response.Redirect("/?登陆成功" + ((UserInfo)Session["user"]).UserName);
                        }
                    }
                }
            }            
        }
    }
}